using B.S.Data.MES.API.Applications.BaseData.Command.ProductMaterialCommand;
using B.S.Domain.BasicData.MaterialManagement.Product_material;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Data.MES.API.Applications.BaseData.CommandHandlers.ProductMaterialCommandHandlers
{
    /// <summary>
    /// 批量删除产品物料处理器
    /// </summary>
    public class PLDeleteProductMaterialCommandHandler : IRequestHandler<PLDeleteProductMaterialCommand, APIRequst<int>>
    {
        private readonly IBaseRepository<Product_material> _productMaterialRepository;

        public PLDeleteProductMaterialCommandHandler(IBaseRepository<Product_material> productMaterialRepository)
        {
            _productMaterialRepository = productMaterialRepository;
        }

        public async Task<APIRequst<int>> Handle(PLDeleteProductMaterialCommand request, CancellationToken cancellationToken)
        {
            APIRequst<int> response = new APIRequst<int>();
            response.Code = RequstCode.成功;
            response.Msg = RequstCode.成功.ToString();

            // 查询要删除的产品物料
            var productMaterials = _productMaterialRepository.GetAll()
                .Where(pm => request.ProductIds.Contains(pm.Productid))
                .ToList();

            // 执行软删除
            foreach (var productMaterial in productMaterials)
            {
                productMaterial.isDel = true;
                productMaterial.DeleteTime = DateTime.Now;
            }

            // 批量更新
            await _productMaterialRepository.UpdateRange(productMaterials);
            response.Data = productMaterials.Count;

            return response;
        }
    }
}